package com.yuncheng.spcyApi.utils;

import com.aspose.words.Document;
import com.aspose.words.ImportFormatMode;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import java.io.*;

@Component(value = "wordPdfUtils")
public class WordPdfUtils {
    private static final Logger log = LoggerFactory.getLogger(WordPdfUtils.class);

    public static void main(String[] args) throws Exception {
//        String srcfile = "C:/upFiles/2023-02-21/药品GMP检查会议签到表.doc";
//        ByteArrayToFile(convertDocIs2DocxIs( new FileInputStream(new File(srcfile))),"C:/upFiles/2023-02-21/at.docx") ;

        String outF = "C:/upFiles/2023-02-21/药品GMP符合性检查报告.docx";
        WordPdfUtils.wordToPdf(outF,"C:/upFiles/2023-02-21/agag.pdf");
    }

    /** 字节数组到文件的过程 */
    public static void ByteArrayToFile(byte[] data,String newFileNmae) {
        File file = new File(newFileNmae);
        //选择流
        FileOutputStream fos = null;
        ByteArrayInputStream bais = null;
        try {
            bais = new ByteArrayInputStream(data);
            fos = new FileOutputStream(file);
            int temp;
            byte[] bt = new byte[1024*10];
            while((temp = bais.read(bt))!= -1) {
                fos.write(bt,0,temp);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关流
            try {
                if(null != fos)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /** 将doc输入流转换为docx输入流 */
    private static byte[] convertDocIs2DocxIs(InputStream docInputStream) throws IOException {
        getLicense();
        byte[] docBytes = FileCopyUtils.copyToByteArray(docInputStream);
        byte[] docxBytes = convertDocStream2docxStream(docBytes);
        return docxBytes;
    }

    /** 将doc字节数组转换为docx字节数组 */
    private static byte[] convertDocStream2docxStream(byte[] arrays) {
        byte[] docxBytes = new byte[1];
        if (arrays != null && arrays.length > 0) {
            try (
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    InputStream sbs = new ByteArrayInputStream(arrays)
            ) {
                Document doc = new Document(sbs);
                doc.save(os, SaveFormat.DOCX);
                docxBytes = os.toByteArray();
            } catch (Exception e) {
                log.error("文档转换出错了：{}",e.getMessage());
            }
        }
        return docxBytes;
    }

    /**
     * 加载license 用于破解 不生成水印
     */
    private static void getLicense() {
        Resource resource = new ClassPathResource("excelTemplate/license.xml");

        InputStream inputStream = null;
        try {
            inputStream = resource.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            License license = new License();
            license.setLicense(inputStream);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * word转pdf
     *
     * @param wordPath word文件保存的路径
     * @param pdfPath  转换后pdf文件保存的路径
     */
    public static boolean wordToPdf(String wordPath, String pdfPath) {
        getLicense();
        File file = new File(pdfPath);
        try (FileOutputStream os = new FileOutputStream(file)) {
            Document doc = new Document(wordPath);
            doc.save(os, SaveFormat.PDF);

            return true;
        }catch (Exception e){
            log.error("word转pdf失败：{}", e.getMessage());

            return false;
        }
    }

    /**
     * word转pdf
     * @param wordPath word文件保存的路径
     * @param pdfPath  转换后pdf文件保存的路径
     */
    public static void wordToPdf2(String wordPath, String pdfPath) {
        getLicense();
        File file = new File(pdfPath);
        try (FileOutputStream os = new FileOutputStream(file)) {
            Document doc = new Document(wordPath);
            Document document = new Document();//新建一个空白pdf文档
            document.removeAllChildren();
            document.appendDocument(doc, ImportFormatMode.USE_DESTINATION_STYLES); //保留样式
            document.save(os, SaveFormat.PDF);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * word转html
     *
     * @param orgPath word文件保存的路径
     * @param outPath  转换后文件保存的路径
     */
    public static void wordToHtml(String orgPath, String outPath) {
        getLicense();
        File file = new File(outPath);
        try (FileOutputStream os = new FileOutputStream(file)) {
            Document doc = new Document(orgPath);
            doc.save(os, SaveFormat.HTML);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取html文件内容
     * @param orgPath
     */
    public static String getHtmlFileContent(String orgPath){
        try {
            // 使用Jsoup的parse方法读取文件
            org.jsoup.nodes.Document doc = Jsoup.parse(new File(orgPath), "UTF-8");

            // 输出整个HTML文档
//            System.out.println(doc.html());
            return doc.html();

        }catch (Exception e){

        }

        return "";
    }

    /**
     * doc 转 docx
     *
     * @param orgPath word文件保存的路径
     * @param outPath  转换后文件保存的路径
     */
    public static void wordToDocx(String orgPath, String outPath) {
        getLicense();
        File file = new File(outPath);
        try (FileOutputStream os = new FileOutputStream(file)) {
            Document doc = new Document(orgPath);
            doc.save(os, SaveFormat.DOCX);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /** 验证文Pdf件是否损坏 */
    public static boolean isPdfCorrupted(String filePath) {
        try (PdfReader reader = new PdfReader(new File(filePath));
             PdfDocument pdfDoc = new PdfDocument(reader)) {
            // 如果能成功加载PDF文件，则认为文件没有损坏
            return false;
        } catch (Exception e) {
            // 如果在加载过程中抛出异常，则认为文件可能已损坏
            log.error("验证文Pdf件是否损坏-文件已损坏：{}", filePath);
            return true;
        }
    }
}
